// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import Fk
import Fk.Pages
import Fk.RoomElement

GraphicsBox {
  id: root

  // property var refreshitems: []
  property var repgens: []
  property var friend_cards: []
  property var friend_seats: []
  property list<string> my_cards: []
  property string friend_not_determ: ""
  property string friend_selected: ""
  property string selected
  property int correctspace: 0
  property int correctbottom: 0
  property int repcount: 0
  property bool initial: true

  width: 715
  height: friends_cardsNode.height + my_column.height + title.height + buttonArea.height + correctspace + correctbottom

  Item {
    id: my_column
    visible:my_cards.length > 0
    width: 700
    height: 110
    anchors.top: title.bottom
    // anchors.topMargin: 3
    anchors.left: root.left
    anchors.leftMargin: 10

    Text {
      id: myseltitle
      anchors.top: parent.top
      anchors.horizontalCenter: parent.horizontalCenter
      text:  "我的将池"
      color: "#90EE90"
      font.family: fontLibian.name
      font.bold: true
      font.pixelSize: 23
      style: Text.Outline
      wrapMode: Text.WordWrap
      verticalAlignment: Text.AlignVCenter
      horizontalAlignment: Text.AlignHCenter
    }

    Flickable {
      id:mygensFlick
      visible:my_cards.length > 0
      flickableDirection: Flickable.HorizontalFlick
      anchors.top: myseltitle.bottom
      // anchors.topMargin: 3
      width: 700
      height: mygensLayout.height
      contentWidth: 700
      clip: true

      RowLayout {
        id : mygensLayout
        // spacing: 3
        Repeater {
          model: my_cards
          delegate: GeneralCardItem {
            // scale:0.8
            name: modelData
            selectable: true
            chosenInBox: root.selected == name
            selected: root.selected == name
            onClicked: {
              if (!selectable) return;
              if (root.selected == name) {
                root.selected = "";
              } else {
                root.selected = name;                
              }    
              ClientInstance.notifyServer("PushRequest", "updatemini,preselect," + root.selected);          
            }
            onRightClicked: {
              roomScene.startCheat("GeneralDetail", { generals: [modelData] });
            }
          }
        }
      }
    }
  }

  Flickable {
    id: friends_cardsNode
    visible: friend_cards.length > 0
    // ScrollBar.vertical: ScrollBar {}
    flickableDirection: Flickable.VerticalFlick
    width: 700
    height: friendsFlick.height
    contentHeight: friendsFlick.height
    clip: true

    anchors.top: my_column.bottom
    anchors.topMargin: root.correctspace
    anchors.left: my_column.left
  
    Column {
      id: friendsFlick
      spacing: 5
      Repeater {
        id:friendRepeater
        model: friend_cards

        delegate : Item {
          // property int itemseat: friend_seats.length > 0 ? friend_seats[index] : 0
          width: friends_cardsNode.width
          height: othertitle.height + othergensflick.height

          Text {
            id: othertitle
            anchors.top: parent.top
            anchors.horizontalCenter: parent.horizontalCenter
            // width: 20
            // height: 100
            text:  friend_seats.length > 0 ? friend_seats[index] + "队友将池" : "队友将池"
            color: "white"
            font.family: fontLibian.name
            font.pixelSize: 22
            style: Text.Outline
            wrapMode: Text.WordWrap
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
          }

          Flickable {
            id : othergensflick
            anchors.top: othertitle.bottom
            flickableDirection: Flickable.HorizontalFlick
            width: root.width
            height: 125
            contentWidth: 700
            clip: true

            RowLayout {
              id : othergensLayout
              spacing: 3
              Repeater {
                model: modelData

                delegate: GeneralCardItem {
                  // scale:0.8
                  id:friend_gencard
                  name: modelData
                  selectable: root.friend_selected == ""
                  chosenInBox: root.selected == name
                  selected: root.selected == name
                  onRightClicked: {
                    roomScene.startCheat("GeneralDetail", { generals: [modelData] });
                  }
                  Image {
                    source: AppPath + "/ packages/newlang/image/determ.png"
                    // visible: false
                    visible: friend_selected == modelData
                    anchors.horizontalCenter: parent.horizontalCenter
                    y: 90
                    scale: 0.75
                  }
                  Image {
                    source: AppPath + "/ packages/newlang/image/recommend.png"
                    // visible: false
                    visible: friend_not_determ == modelData
                    anchors.horizontalCenter: parent.horizontalCenter
                    y: 50
                    scale: 0.75
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  Item {
    id: buttonArea
    width: parent.width
    height: 40
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 5

    Row {
      anchors.horizontalCenter: parent.horizontalCenter
      spacing: 8

      MetroButton {
        id: repButton
        text: "换将（剩余" + repcount + "次）"
        // width: 135
        // height: 35
        enabled: root.selected !== "" && repcount > 0

        onClicked: {
          if (repgens.length == 0 || repcount == 0) { return }
          let repg = repgens.shift()
          for(let i = 0;i < my_cards.length;i++){
            if(my_cards[i] == root.selected){
              my_cards[i] = repg
            }
          }
          repcount = repcount - 1;
          ClientInstance.notifyServer("PushRequest", "updatemini,updataRepGen," + root.selected);
        }
      }

      MetroButton {
        id: fightButton
        text: luatr("Fight")
        width: 100
        height: 35
        enabled: root.selected !== ""

        onClicked: {
          close();
          roomScene.state = "notactive";
          ClientInstance.notifyServer("PushRequest", "updatemini,select," + root.selected);
          ClientInstance.replyToServer("", JSON.stringify(root.selected));
        }
      }

      MetroButton {
        id: detailBtn
        enabled: root.selected !== ""
        text: luatr("Show General Detail")
        onClicked: roomScene.startCheat(
          "GeneralDetail",
          { generals: [root.selected] }
        );
      }
    }
  }

  function loadData(data) {
    let scalenum = 1
    if (data.othergens.length == 2){
      scalenum = 0.9
      correctspace = 20
      correctbottom = 10
    }else if (data.othergens.length >= 3){
      scalenum = 0.85
      correctspace = 0
      correctbottom = 0
      // root.y = Math.round(roomArea.height * 0.8 - root.height / 2) + 50
    }else if (data.othergens.length <= 1){
      correctspace = 50
      correctbottom = 20
    }
    root.title.text = "你的座次是<font color='red'><b>" + roomScene.getPhoto(Self.id).seatNumber + "</b></font>号, 请选择";

    friend_seats = data.otherseats;
    my_cards = data.gens;
    friend_cards = data.othergens;
    repgens = data.repgens;
    repcount = data.repcount;

    my_column.scale = scalenum;
    friends_cardsNode.scale = scalenum;

    root.scale = scalenum;
    // console.log(friends_cardsNode.height)
    if(data.othergens.length >= 2){
      delayYTimer.start()
    }
  }

  Timer {
    id: delayYTimer
    interval: 10  // 设置延时时间，单位为毫秒
    onTriggered: {
      // 这里是延时后要执行的代码
      // console.log("延时已触发，执行代码")
      // console.log(root.y)
      root.y = (friend_cards.length - 1) * 27 + root.y
    }
  }

  // Component.onCompleted: {
  //   console.log("组件加载结束显示y位置")
  //   root.y = 140
  //   console.log(root.y)
  // }

  function updateData(data) {
    let [type, value] = data;
    // console.log(type)
    // console.log(value)
    value = value ?? "";
    if (type == "preselect") {
      friend_not_determ = value;
      // for(let i = 0;i < friendRepeater.count;i++){
      //   let item = friendRepeater.itemAt(i);
      //   if(item.itemseat == friendpos){
      //     item.itemAt()
      //   }
      // }
    } else if (type == "select") {
      friend_not_determ = "";
      friend_selected = value;
    } else if (type == "updataRepGen") {
      if (repgens.length == 0) { return }
      let isrep = false;
      for(let i = 0;i < friend_cards.length;i++){
        let friendges = friend_cards[i]
        // console.log(friendges)
        for(let j = 0;j < friendges.length;j++){
          if(friendges[j] === value){
            let repg = repgens.shift()
            // console.log("新替的将领："+ repg)
            friend_cards[i][j] = repg
            isrep = true
            break;
          }
        }
        if (isrep) {break;}
      }
      // console.log(friend_cards)
      friendRepeater.model = friend_cards
    } else if (type == "updateFriendCards") {
      friend_cards = value.split("|");
    }
  }
}
